package uit.uthuoc.dal;

import java.io.*;
import java.util.ArrayList;

import uit.uthuoc.utils.StringUtils;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.KeyCharacterMap.UnavailableException;
import android.widget.Toast;



public class DrugDAO {
	protected static final String LOG_ID = "uit.uThuoc.dal.DrugDAO";
	
	
	private ArrayList<DrugDTO> mDrugs;
	
	private static final String TBL_DRUG = "thuoc";
	private static final String COL_ID = "id";
	private static final String COL_NAME = "ten_thuoc";
	private static final String COL_CODE = "ma_thuoc";
	private static final String COL_MANUFACTURER = "nha_san_xuat";
	private static final String COL_DISTRIBUTOR = "nha_phan_phoi";
	private static final String COL_CONTENT = "thanh_phan";
	private static final String COL_INDICATIONS = "chi_dinh";
	private static final String COL_DOSAGE = "lieu_dung";
	private static final String COL_ADMINISTRATION = "cach_dung";
	private static final String COL_CONTRAINDICATIONS = "chong_chi_dinh";
	private static final String COL_SPECIAL_PRECAUTIONS = "than_trong";
	private static final String COL_ADVERSE_REACTIONS = "phan_ung_co_hai";
	private static final String COL_INTERACTIONS = "tuong_tac_thuoc";
	private static final String COL_MIMS_CLASS = "phan_loai";
	private static final String COL_PACKAGE = "dong_goi";
	private static final String COL_NOTE = "ghi_chu";
	private static final String COL_NAME_ASCII = "ten_thuoc_ascii";
	public static final String DB_DEFAULT_VALUE = "u";
	
	private static final String TBL_MIMSCLASS = "phan_loai";
	private static final String COL_MIMSCLASS_ID = "id";
	private static final String COL_MIMSCLASS_NAME = "ten_phan_loai";
	private static final String COL_MIMSCLASS_NAME_ASCII = "ten_phan_loai_ascii";
	private static final String COL_MIMSCLASS_CODE = "ma_phan_loai";
	
	private static final String COMPARE_TYPE_LIKE = " LIKE ";
	private static final String COMPARE_TYPE_EQUAL = " = ";
	
	private static DrugDAO sDrugDAO;
	private static final String sDBName = "uthuoc.sqlite";
	private static String sDBPath;
	private static Context context;
	private SQLiteDatabase mDatabase;
	
	
	
	private DrugDAO() {
		if(android.os.Build.VERSION.SDK_INT >= 17){
			sDBPath = context.getApplicationInfo().dataDir + "/databases/";         
	    }
	    else
	    {
	    	sDBPath = "/data/data/" + context.getPackageName() + "/databases/";
	    }
		sDBPath += sDBName;
		
		mDrugs = new ArrayList<DrugDTO>();
		
		// copy database
		if (!checkDataBaseExist())
		{
			mDatabase = context.openOrCreateDatabase(sDBName, Context.MODE_PRIVATE, null);
			try {
				copyDataBase();
				Log.e(LOG_ID, "copy thanh cong");
			} catch (IOException mIOException) 
	        {
				Log.e(LOG_ID, "copy THAT BAI");
	            throw new Error("ErrorCopyingDataBase");
	        }
			
		}
		
		mDatabase = context.openOrCreateDatabase(sDBName, Context.MODE_PRIVATE, null);

		
		
	/*	for (int i = 0; i < 100; i++) {
			DrugDTO temp = new DrugDTO();
			temp.setDrugName("Drug #" + i);
			mDrugs.add(temp);
		}*/
	}
	
	public static void setContext(Context ctx){
		context = ctx;
		Log.e(LOG_ID, "Context setted");
	}
	
	public static DrugDAO getDAO() {
		if (sDrugDAO == null) {
			sDrugDAO = new DrugDAO();
		}
		
		return sDrugDAO;
	}
	
	// 
	protected ArrayList<DrugDTO> searchDrug(String column, String compareType, String searchStr) {
		mDrugs.clear();
		
		String compareValue = searchStr;
		if (compareType == COMPARE_TYPE_LIKE)
		{
			compareValue = "%" + searchStr + "%";
		}
		
		Cursor c = mDatabase.query(TBL_DRUG, new String[]{
						COL_ID, COL_CODE, COL_NAME, 
						COL_MANUFACTURER, COL_DISTRIBUTOR, COL_CONTENT, 
						COL_INDICATIONS, COL_DOSAGE, COL_ADMINISTRATION, 
						COL_CONTRAINDICATIONS, COL_SPECIAL_PRECAUTIONS, COL_ADVERSE_REACTIONS, 
						COL_INTERACTIONS, COL_MIMS_CLASS, COL_PACKAGE}, 
					column + compareType +" ?", new String[]{compareValue}, null, null, null); 
		c.moveToFirst();
		while (c.isAfterLast() == false)
		{
			DrugDTO temp = new DrugDTO();
			temp.setID(Integer.parseInt(c.getString(0)));
			temp.setDrugCode(c.getString(1));
			temp.setDrugName(c.getString(2).trim());
			temp.setManufacturer(c.getString(3));
			temp.setDistributor(c.getString(4));
			temp.setContent(c.getString(5));
			temp.setIndications(c.getString(6));
			temp.setDosage(c.getString(7));
			temp.setAdministration(c.getString(8));
			temp.setContraindications(c.getString(9));
			temp.setSpecialPrecautions(c.getString(10));
			temp.setAdverseReactions(c.getString(11));
			temp.setInteractions(c.getString(12));
				/// get MIMSClass from table phan_loai
			Cursor cursorMIMSClass = mDatabase.query(TBL_MIMSCLASS, new String[] {COL_MIMSCLASS_ID, COL_MIMSCLASS_CODE, COL_MIMSCLASS_NAME}, COL_MIMSCLASS_ID + " = ?", new String[] {c.getString(13)}, null, null, null);
			cursorMIMSClass.moveToFirst();
			MIMSClassDTO tempMIMS = new MIMSClassDTO();
			tempMIMS.setID(Integer.parseInt(cursorMIMSClass.getString(0)));
			tempMIMS.setMIMSClassCode(cursorMIMSClass.getString(1));
			tempMIMS.setMIMSClassName(cursorMIMSClass.getString(2));
			temp.setMIMSClass(tempMIMS);
			
			temp.setPackage(c.getString(14));
			
			mDrugs.add(temp);
			
			c.moveToNext();
		}
		return mDrugs;
	}
	
	protected ArrayList<DrugDTO> searchDrug(String columnUnicode, String columnAscii, String compareType, String searchStr) {
		mDrugs.clear();
		
		String compareValue = searchStr;
		if (compareType == COMPARE_TYPE_LIKE)
		{
			compareValue = "%" + searchStr + "%";
		}
		
		Cursor c = mDatabase.query(TBL_DRUG, new String[]{
						COL_ID, COL_CODE, COL_NAME, 
						COL_MANUFACTURER, COL_DISTRIBUTOR, COL_CONTENT, 
						COL_INDICATIONS, COL_DOSAGE, COL_ADMINISTRATION, 
						COL_CONTRAINDICATIONS, COL_SPECIAL_PRECAUTIONS, COL_ADVERSE_REACTIONS, 
						COL_INTERACTIONS, COL_MIMS_CLASS, COL_PACKAGE}, 
					columnUnicode + compareType +" ? OR " + columnAscii + compareType + " ?", new String[]{compareValue, compareValue}, null, null, null); 
		c.moveToFirst();
		while (c.isAfterLast() == false)
		{
			DrugDTO temp = new DrugDTO();
			temp.setID(Integer.parseInt(c.getString(0)));
			temp.setDrugCode(c.getString(1));
			temp.setDrugName(c.getString(2).trim());
			temp.setManufacturer(c.getString(3));
			temp.setDistributor(c.getString(4));
			temp.setContent(c.getString(5));
			temp.setIndications(c.getString(6));
			temp.setDosage(c.getString(7));
			temp.setAdministration(c.getString(8));
			temp.setContraindications(c.getString(9));
			temp.setSpecialPrecautions(c.getString(10));
			temp.setAdverseReactions(c.getString(11));
			temp.setInteractions(c.getString(12));
				/// get MIMSClass from table phan_loai
			Cursor cursorMIMSClass = mDatabase.query(TBL_MIMSCLASS, new String[] {COL_MIMSCLASS_ID, COL_MIMSCLASS_CODE, COL_MIMSCLASS_NAME}, COL_MIMSCLASS_ID + " = ?", new String[] {c.getString(13)}, null, null, null);
			cursorMIMSClass.moveToFirst();
			MIMSClassDTO tempMIMS = new MIMSClassDTO();
			tempMIMS.setID(Integer.parseInt(cursorMIMSClass.getString(0)));
			tempMIMS.setMIMSClassCode(cursorMIMSClass.getString(1));
			tempMIMS.setMIMSClassName(cursorMIMSClass.getString(2));
			temp.setMIMSClass(tempMIMS);
			
			temp.setPackage(c.getString(14));
			
			mDrugs.add(temp);
			
			c.moveToNext();
		}
		return mDrugs;
	}
	
	public ArrayList<DrugDTO> searchDrugByDrugName(String searchStr) {
		//return searchDrug(COL_NAME, COMPARE_TYPE_LIKE, searchStr);
		return searchDrug(COL_NAME, COL_NAME_ASCII, COMPARE_TYPE_LIKE, searchStr);
	}
	
	public ArrayList<DrugDTO> searchDrugByMIMSClass(String searchStr) {
		return searchDrug(COL_MIMS_CLASS, COMPARE_TYPE_EQUAL, searchStr);
	}
	
	public ArrayList<MIMSClassDTO> searchMIMSClass(String column, String compareType, String searchStr){
		ArrayList<MIMSClassDTO> mMIMSClasses = new ArrayList<MIMSClassDTO>();
		
		String compareValue = searchStr;
		if (compareType == COMPARE_TYPE_LIKE)
		{
			compareValue = "%" + searchStr + "%";
		}
		Cursor cursorMIMSClass = mDatabase.query(TBL_MIMSCLASS, new String[] {COL_MIMSCLASS_ID, COL_MIMSCLASS_CODE, COL_MIMSCLASS_NAME}, 
								column + compareType + " ?", new String[] {compareValue}, null, null, null);
		cursorMIMSClass.moveToFirst();
		while (cursorMIMSClass.isAfterLast() == false)
		{
			MIMSClassDTO temp = new MIMSClassDTO();
			
			temp.setID(Integer.parseInt(cursorMIMSClass.getString(0)));
			temp.setMIMSClassCode(cursorMIMSClass.getString(1));
			temp.setMIMSClassName(cursorMIMSClass.getString(2));
			
			
			mMIMSClasses.add(temp);
			cursorMIMSClass.moveToNext();
		}
		return mMIMSClasses;
	}
	
	public ArrayList<MIMSClassDTO> searchMIMSClass(String columnUnicode, String columnAscii, String compareType, String searchStr){
		ArrayList<MIMSClassDTO> mMIMSClasses = new ArrayList<MIMSClassDTO>();
		
		String compareValue = searchStr;
		
		if (compareType == COMPARE_TYPE_LIKE)
		{
			compareValue = "%" + compareValue + "%";
			
		}
		Cursor cursorMIMSClass = mDatabase.query(TBL_MIMSCLASS, new String[] {COL_MIMSCLASS_ID, COL_MIMSCLASS_CODE, COL_MIMSCLASS_NAME}, 
						columnUnicode + compareType + " ? OR " + columnAscii + compareType + " ?", 
						new String[] {compareValue, compareValue}, null, null, null);
		cursorMIMSClass.moveToFirst();
		while (cursorMIMSClass.isAfterLast() == false)
		{
			MIMSClassDTO temp = new MIMSClassDTO();
			
			temp.setID(Integer.parseInt(cursorMIMSClass.getString(0)));
			temp.setMIMSClassCode(cursorMIMSClass.getString(1));
			temp.setMIMSClassName(cursorMIMSClass.getString(2));
			
			
			mMIMSClasses.add(temp);
			cursorMIMSClass.moveToNext();
		}
		return mMIMSClasses;
	}
	
	public ArrayList<MIMSClassDTO> searchMIMSClassByMIMSClassName(String searchStr){
		
		//return searchMIMSClass(COL_MIMSCLASS_NAME_ASCII, COMPARE_TYPE_LIKE, searchStr);
		return searchMIMSClass(COL_MIMSCLASS_NAME, COL_MIMSCLASS_NAME_ASCII, COMPARE_TYPE_LIKE, searchStr);
	}
	
	public MIMSClassDTO searchMIMSClassByMIMSClassID(int id){
		return searchMIMSClass(COL_MIMSCLASS_ID, COMPARE_TYPE_EQUAL, Integer.toString(id)).get(0);
	}

	public DrugDTO getDrug(int index) {
		return mDrugs.get(index);
	}
	
	//Copy the database from assets
    private void copyDataBase() throws IOException
    {
        InputStream mInput = context.getAssets().open(sDBName);
        OutputStream mOutput = new FileOutputStream(sDBPath);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer))>0)
        {
            mOutput.write(mBuffer, 0, mLength);
        }
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }
    
  //Check that the database exists
    private boolean checkDataBaseExist()
    {
        File dbFile = new File(sDBPath);
   /*     if (dbFile.exists()) {
        	Log.e(LOG_ID, "db ton tai");
        } else Log.e(LOG_ID, "db KHONG ton tai");
*/        
        return dbFile.exists();
    }
}
